package service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import bean.Teacher;
import service.LoginService;

@Service @Transactional
public class LoginServiceBean implements LoginService{
	@Resource SessionFactory factory;

	@Override
	public Teacher findTeacherByUsername(String tusername) {
	
		if(tusername.indexOf("@")!=-1)			//邮箱登录
		{
			return findTeacherByEmail(tusername);
		}
		return findTeacherByPhone(tusername);	//手机登录
	}
	
	@Override
	public void updateTeacher(Teacher teacher) {
		factory.getCurrentSession().merge(teacher);	
	}


	@Override
	public Teacher findTeacherByEmail(String temail) {
		@SuppressWarnings("unchecked")
		List<Teacher> teachers = factory.getCurrentSession().createQuery("from Teacher where temail = ?").
				setParameter(0, temail).list();
					if(teachers.isEmpty())
					{
						return null;
					}
					return teachers.get(0);
	}

	@Override
	public Teacher findTeacherByPhone(String tphone) {
		@SuppressWarnings("unchecked")		
		List<Teacher> teachers = factory.getCurrentSession().createQuery("from Teacher where tphone = ?").
				setParameter(0, tphone).list();
					if(teachers.isEmpty())
					{
						return null;
					}
					return teachers.get(0);
	}

	@Override
	public int addTeacher(Teacher teacher) {
		List<Teacher> teacherlist = getAllTeacher();
		if(teacherlist.size() != 0)
		{
			for(int i = 0; i < teacherlist.size(); i++)
			{
				if(teacherlist.get(i).getTemail().equals(teacher.getTemail()))
				{
					return -2;				//-2表示email已存在
				}
				if(teacher.getTphone() != null)
				{
					if(teacherlist.get(i).getTphone().equals(teacher.getTemail()))
					{
						return -1;			//-1表示手机号已存在
					}
				}
			}
		}
	
		factory.getCurrentSession().persist(teacher);
		return teacher.getId();				//返回id作为手机端的tid
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Teacher> getAllTeacher() {
		return factory.getCurrentSession().createQuery("from Teacher").list();
	}

	@Override
	public Teacher findTeacherById(int tid) {
		return (Teacher) factory.getCurrentSession().get(Teacher.class, tid);
	}

}
